package com.ncs.controller.manager_controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ncs.entity.PageResult;
import com.ncs.entity.QueryPageBean;
import com.ncs.entity.Result;
import com.ncs.pojo.PhoneManager;
import com.ncs.pojo.Reservation;
import com.ncs.pojo.Table;
import com.ncs.service.ReservationService;
import com.ncs.service.TableService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 今日任务：
 完成后台管理系统预定管理的后端代码编写
 解决若干小问题
 任务进展：完成

 前后端传输日期格式问题，后端实体类添加
 @DateTimeFormat(pattern = "yyyy-MM-dd")
 @JsonFormat(pattern = "yyyy-MM-dd",timezone="GMT+8

 学习vue
 */
@CrossOrigin
@RestController
@RequestMapping("/manager/reservation")
public class ManageReservationController {
    @Autowired
    ReservationService reservationService;
    @Autowired
    TableService tableService;
    @PostMapping("/getpage")
    /**分页查询**/
    Result getPage(@RequestBody QueryPageBean queryPageBean){
        Result result = new Result();
        try {
//            当前页
            Integer currentPage = queryPageBean.getCurrentPage();
//            页面大小
            Integer pageSize = queryPageBean.getPageSize();
//            分页查询
            Page<Reservation> adminPage = new Page<Reservation>(currentPage, pageSize);
            QueryWrapper<Reservation> adminQueryWrapper = new QueryWrapper<>();
            if (queryPageBean.getQueryString() != null) {
                adminQueryWrapper.like("phone", queryPageBean.getQueryString());
            }
            Page<Reservation> page = reservationService.page(adminPage, adminQueryWrapper);
//            设置分页查询返回值
            PageResult pageResult = new PageResult();
            pageResult.setRows(page.getRecords());
            pageResult.setTotal(page.getTotal());
            result.setData(pageResult);
            result.setFlag(true);
            result.setMessage("查询成功");

        }catch (Exception e){
//            异常处理
            result.setFlag(false);
            result.setMessage(e.getMessage());
        }
        return  result;

    }
    @Transactional//多表操作，加入事务管理控制
    @PostMapping("/toUpdate")
    /**分页查询**/
    Result toUpdate(@RequestBody Reservation reservation){
        Result result = new Result();
        try {


            //对更新前原本的餐桌号进行状态的更改
            int tableId = reservation.getTableId();
            Reservation reservationFromDB = reservationService.getById(reservation.getId());
            QueryWrapper<Table> qw = new QueryWrapper<>();
            qw.eq("id",reservationFromDB.getTableId());
            Table table1 = new Table();
            table1.setState("free");
            tableService.update(table1,qw);
            //对更新前原本的餐桌号进行状态的更改
            UpdateWrapper<Reservation> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id",reservation.getId());
            reservationService.update(reservation,updateWrapper);
            //对更新后的新餐桌号进行更改
            UpdateWrapper<Table> wp = new UpdateWrapper<Table>();
            wp.eq("id", tableId);
            Table table = new Table();
            table.setState("used");
            tableService.update(table,wp);

            result.setFlag(true);
            result.setMessage("更新成功");

        }catch (Exception e){
//            异常处理
            result.setFlag(false);
            result.setMessage("更新失败");
        }
        return  result;

    }
    @Transactional//多表操作，加入事务管理控制
    @PostMapping("/toAdd")
    /**分页查询**/
    Result toAdd(@RequestBody Reservation reservation){
        Result result = new Result();
        try {
            reservationService.save(reservation);
            int tableId = reservation.getTableId();
            UpdateWrapper<Table> wp = new UpdateWrapper<Table>();
            wp.eq("id", tableId);
            Table table = new Table();
            table.setState("used");
            tableService.update(table,wp);
            result.setFlag(true);
            result.setMessage("添加成功");

        }catch (Exception e){
//            异常处理
            result.setFlag(false);
            result.setMessage("添加失败");
        }
        return  result;

    }
    @Transactional//多表操作，加入事务管理控制
    @DeleteMapping("/toDelete/{id}/{tableId}")
    /**分页查询**/
    Result toDelete(@PathVariable int id,@PathVariable int tableId){
        Result result = new Result();
        try {
//            Reservation byId = reservationService.getById(id);
            UpdateWrapper<Table> wp = new UpdateWrapper<Table>();
            wp.eq("id", tableId);
            Table table = new Table();
            table.setState("free");
            tableService.update(table,wp);
            reservationService .removeById(id);
            result.setFlag(true);
            result.setMessage("删除成功");
        }catch (Exception e){
//            异常处理
            result.setFlag(false);
            result.setMessage("删除失败");
        }
        return  result;

    }

    @GetMapping("/getTables")
    public Result getTables(Table table) {
        Result result = new Result();

        try{
            //构造查询条件
            LambdaQueryWrapper<Table> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            //添加条件，查询状态为free的（空闲状态）
            lambdaQueryWrapper.eq(Table::getState, "free");
            lambdaQueryWrapper.eq(table.getId() != null, Table::getId, table.getId());
            //条件排序条件
            lambdaQueryWrapper.orderByAsc(Table::getId);

            List<Table> tableList = tableService.list(lambdaQueryWrapper);
            result.setData(tableList);
            result.setFlag(true);
            result.setMessage("查询成功");
        }catch(Exception e){
//            异常处理
            result.setFlag(false);
            result.setMessage("删除失败");
        }
        return result;
    }
}
